package com.uenpay.im.pay;

import android.text.TextUtils;
import android.util.Log;

import com.socks.library.KLog;
import com.uenpay.im.IMApplication;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.invokeitems.HttpPostRequest;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @Author: SL
 * @Date: 2017/1/10 14:54
 * @CopyRight: http://www.qiyunxin.com
 * @Parameter: TODO
 * @Function: 支付相关
 */
public class PayHandle {
    private static final String TAG = "PayHandle";
    public interface IGetPayTokenResult {
        void onResult(int status, String payToken);
    }

    /**
     * 获取支付token
     *
     * @param payPwd              支付密码
     * @param mIGetPayTokenResult
     */
    public static void getPayToken(String payPwd, final IGetPayTokenResult mIGetPayTokenResult) {
        Log.d(TAG, "getPayToken: "+payPwd);
        String url = APIConfiguration.getPayUrl() + "useraccounts/" + IMApplication.getInstance().getUcrOpendId() + "/paytoken";
        KLog.d(TAG,"url="+url);
        JSONObject json = new JSONObject();
        try {
            json.put("password", payPwd);
            HttpPostRequest.onRequest(url, json.toString(), HttpPostRequest.REQUESTMETHOD_POST, new HttpPostRequest.IRequest() {
                @Override
                public void onResult(int responseCode, String response) {
                    KLog.d("responseCode="+responseCode+" response="+response);
                    if (responseCode == 200) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.has("pay_token")) {
                                mIGetPayTokenResult.onResult(0, jsonObject.optString("pay_token"));
                            } else {
                                mIGetPayTokenResult.onResult(-1, "");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject json = new JSONObject(response);
                                mIGetPayTokenResult.onResult(json.optInt("err_code"), json.optString("err_msg"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
